package com.web.portal.controller.common;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;
import com.web.portal.pojo.Article;
import com.web.portal.pojo.LabelArticle;
import com.web.portal.pojo.LabelInfo;
import com.web.portal.pojo.PortalUser;
import com.web.portal.pojo.query.ArticleQuery;
import com.web.portal.pojo.response.ArticleAndUserAndLabel;
import com.web.portal.response.ResponseResult;
import com.web.portal.services.*;
import com.web.portal.utils.IdWorker;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;

/**
 * 文章
 */
@Slf4j
@Api(tags = "文章管理")
@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private Gson gson;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private ArticleService articleService;
    @Autowired
    private UserService userService;
    @Autowired
    private ICategoryService iCategoryService;
    @Autowired
    private LabelArticeService labelArticeService;
    @Autowired
    private LabelInfoService labelInfoService;


    /**
     * 添加文章
     * 需要管理员权限
     *
     * @param article
     * @return
     */
    @PostMapping
    @ApiOperation(value = "添加文章")
    public ResponseResult addArticle(@RequestBody Article article) {
        article.setArticleCode(idWorker.nextId() + "");
        if (iCategoryService.getById(article.getCategoryId()) == null) {
            return ResponseResult.FAILED("请添加正确的类型");
        }
        PortalUser checkSobUser = userService.checkSobUser();
        article.setUserCode(checkSobUser.getUserCode());
        boolean flag = articleService.save(article);
        if (flag) {
            return ResponseResult.SUCCESS("添加成功");
        } else {
            return ResponseResult.FAILED("添加失败");
        }
    }


    /**
     * 用id获取文章
     *
     * @param articleId
     * @return
     */
    @ApiOperation(value = "用id获取文章")
    @GetMapping("{ArticleId}")
    public ResponseResult getArticle(@PathVariable("ArticleId") String articleId) {
        Article article = articleService.getById(articleId);
        if (article == null) {
            return ResponseResult.FAILED("查找失败");
        }
        articleService.addReadership(article);
        convert(article);

        return ResponseResult.SUCCESS().setData(article);
    }

    /**
     * 用id获取文章
     *
     * @param articleId
     * @return
     */
    @ApiOperation(value = "用id获取文章 带发布文章用户的数据 ")
    @GetMapping("article_info/{ArticleId}")
    public ResponseResult getArticleAndUser(@PathVariable("ArticleId") String articleId) {
        Article article = articleService.getById(articleId);
        if (article == null) {
            return ResponseResult.FAILED("查找失败");
        }
        articleService.addReadership(article);
        convert(article);

        String articleJson = gson.toJson(article);
        ArticleAndUserAndLabel participant = gson.fromJson(articleJson, ArticleAndUserAndLabel.class);

        List<LabelArticle> labelArticles = labelArticeService.selectByLabelCode(article.getArticleCode());
        List<LabelInfo> articles = new ArrayList<>();
        for (LabelArticle labelArticle : labelArticles) {
            LabelInfo labelInfo = labelInfoService.selectByLabelCode(labelArticle.getLabelCode());
            articles.add(labelInfo);
        }

        participant.setLabelInfos(articles);
        PortalUser portalUser = userService.selectByUserCodeInfo(article.getUserCode());
        participant.setPortalUser(portalUser);

        return ResponseResult.SUCCESS().setData(participant);
    }


    /**
     * 获取文章
     * <p>
     * 权限：管理员权限
     *
     * @return
     */
    @ApiOperation(value = "获取文章")
    @GetMapping("/list")
    public ResponseResult listArticle() {
        return ResponseResult.SUCCESS("获取分类列表成功.")
                .setData(articleService.list());
    }

    /**
     * 已发布分页
     *
     * @param current
     * @param limit
     * @param articleQuery
     * @return
     */
    @ApiOperation(value = "根据 用户名 和文章类型(可为空)获取文章 ")
    @GetMapping("/{current}/{limit}")
    public ResponseResult listArticle(@PathVariable Long current,
                                      @PathVariable Long limit,
                                      ArticleQuery articleQuery) {
        Page<Article> page = new Page<>(current, limit);
        QueryWrapper<Article> wrapper = new QueryWrapper<Article>();
//        String articleType = articleQuery.getArticleType();
//        String userName = articleQuery.getUserName();
        if (!StringUtils.isEmpty(articleQuery.getArticleType())) {
            wrapper.eq("article_type", articleQuery.getArticleType());
        }
        if (!StringUtils.isEmpty(articleQuery.getUserName())) {
            wrapper.eq("user_name", articleQuery.getUserName());
        }
        if (!StringUtils.isEmpty(articleQuery.getCategoryId())) {
            wrapper.eq("category_id", articleQuery.getCategoryId());
        }
        wrapper.eq("state", "0");
        wrapper.orderByDesc("create_time");
        Page<Article> pageHospitalSet = articleService.page(page, wrapper);
        return ResponseResult.SUCCESS("获取文章成功.")
                .setData(pageHospitalSet);
    }


    /**
     * 根据标签分页
     *
     * @param current
     * @param limit
     * @param labelCode
     * @return
     */
    @ApiOperation(value = "根据标签分页")
    @GetMapping("label_info/{current}/{limit}/{label_code}")
    public ResponseResult listLabelInfoArticle(@PathVariable Long current,
                                               @PathVariable Long limit,
                                               @PathVariable("label_code") String labelCode) {

        labelArticeService.getListArticleByLabelCode(current, limit, labelCode);
        return ResponseResult.SUCCESS("获取文章成功.")
                .setData(labelArticeService.getListArticleByLabelCode(current, limit, labelCode));
    }

    /**
     * 发布文章
     *
     * @param article
     * @return
     */
    @ApiOperation(value = "发布文章")
    @PostMapping("release")
    public ResponseResult release(@RequestBody Article article) {
        article.setTextType("1");
        boolean flag = articleService.updateById(article);
        if (flag) {
            return ResponseResult.SUCCESS("更改成功");
        } else {
            return ResponseResult.FAILED("更改失败");
        }
    }

    /**
     * 更新分类
     *
     * @param article
     * @return
     */
    @ApiOperation(value = "更改文章")
    @PostMapping("updateArticle")
    public ResponseResult updateArticle(@RequestBody Article article) {
        if (iCategoryService.getById(article.getCategoryId()) == null) {
            return ResponseResult.FAILED("请添加正确的类型");
        }
        PortalUser portalUser = userService.selectByUserCodeInfo(article.getUserCode());
        if (!portalUser.getUserCode().equals(article.getArticleCode())
                || portalUser.getRoles().equals("0")
                || portalUser.getRoles().equals("1")) {
            return ResponseResult.FAILED("权限不够");
        }
        boolean flag = articleService.updateById(article);
        if (flag) {
            return ResponseResult.SUCCESS("更改成功");
        } else {
            return ResponseResult.FAILED("更改失败");
        }
    }


    @ApiOperation(value = "删除文章")
    @DeleteMapping("/{articleId}")
    public ResponseResult deleteArticle(@PathVariable("articleId") String articleId) {
        PortalUser checkSobUser = userService.checkSobUser();
        if (!checkSobUser.getUserCode().equals(articleService.getById(articleId))
                || checkSobUser.getRoles().equals("0")
                || checkSobUser.getRoles().equals("1")) {
            return ResponseResult.FAILED("权限不够");
        }
        boolean flag = articleService.removeById(articleId);
        if (flag) {
            return ResponseResult.SUCCESS("删除成功");
        } else {
            return ResponseResult.FAILED("删除失败");
        }
    }

    /**
     * 把数字状态转为汉字
     *
     * @param article
     */
    public void convert(Article article) {
        article.setState(getState(article.getState()));
        article.setTextType(getTextType(article.getTextType()));
        article.setArticleType(getArticleType(article.getArticleType()));
    }

    public String getState(String state) {
        switch (state) {
            case "0":
                return "已发布";
            case "1":
                return "草稿";
            case "2":
                return "删除";

            default:
                return state;
        }
    }

    public String getTextType(String textType) {
        switch (textType) {
            case "0":
                return "富文本";
            case "1":
                return "markdown";
            default:
                return textType;
        }
    }

    public String getArticleType(String articleType) {
        switch (articleType) {
            case "1":
                return "新闻";
            case "2":
                return "万花筒";
            default:
                return articleType;
        }
    }
}
